package com.xmy.study.filters;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * shiro没有权限过滤器
 */
public class ShiroPermissionFilter extends PermissionsAuthorizationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        //return super.onAccessDenied(request, response);
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        JSONObject json = new JSONObject();
        Subject subject = this.getSubject(request, response);
        if (subject.getPrincipal() == null) {
            json.put("code","10002");
            json.put("data","");
            json.put("message","登录已失效，请重新登录！");
        } else {
            json.put("code","10003");
            json.put("data","");
            json.put("message","您还没有该权限，请联系管理员！");
        }
        out.println(json);
        out.flush();
        out.close();
        return false;
    }
}
